//
//  AppDelegate.m
//  inquiry
//
//  Created by 高宇 on 2020/5/17.
//  Copyright © 2020 高宇. All rights reserved.
//

#import "AppDelegate.h"
#import "IQKeyboardManager.h"
#import "Interface.h"
#import "ULNetHelper.h"
#import "GXToast.h"
#import "LoginViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;

    //检测版本
    NSDictionary *dic = @{
        @"versionsType":@"ios",
    };
    [ULNetHelper POST:checkVersionPath parameters:dic success:^(id responseObject) {
        NSLog(@"版本信息%@",responseObject);
        NSDictionary *dic = responseObject;
        long code = [dic[@"code"] longValue];
        if (code == 200) {
            NSString *newStr = dic[@"data"][@"versionsNumber"];

            //获取 App 当前版本号
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

            if (![newStr isEqualToString:appVersion]) {
                //更新版本
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"版本有更新" message: @"请前往AppStore更新最新版本后继续使用" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/app/apple-store"]];
                    if([[UIApplication sharedApplication] respondsToSelector:@selector(terminateWithSuccess)]){
                        [[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
                    }
                }]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[self topViewController] presentViewController:alert animated:YES completion:nil];
                });
            }
        }else{

        }
    } failure:^(NSError *error) {
        [GXToast showText:@"网络连接失败, 请优化网络后重新进入"];
    }];
    
    
    //更新服务器配置
    [ULNetHelper POST:initPath parameters:@{} success:^(id responseObject) {
        NSLog(@"服务器配置%@",responseObject);
        NSDictionary *dic = responseObject;
        long code = [dic[@"code"] longValue];
        if (code == 200) {
            
        }
    } failure:^(NSError *error) {
        [GXToast showText:@"网络连接失败, 请优化网络后重新进入"];
    }];
    
    
    //chenk接口(学生触发)
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *type = [user objectForKey:@"type"];  //是否已有登录角色
    if ([type intValue] == 1001) {
        NSString *uuid = [user objectForKey:@"uuid"];
        [ULNetHelper POST:checkPath parameters:@{@"uuid":uuid} success:^(id responseObject) {
            NSDictionary *dic = responseObject;
            long code = [dic[@"code"] longValue];
            if (code == 200) {
                
            }else{
                [GXToast showText:@"登录已过期"];
                // 删除NSUserDefaults所有记录
                NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
                NSUserDefaults * defautls = [NSUserDefaults standardUserDefaults];
                [defautls removePersistentDomainForName:appDomain];
                
                LoginViewController *vc = [[LoginViewController alloc] init];
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                window.rootViewController = vc;
                [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
            }
        } failure:^(NSError *error) {
            [GXToast showText:@"网络连接失败, 请优化网络后重新进入"];
        }];
    }
    return YES;
}

#pragma mark - UISceneSession lifecycle


- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}


- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}


/// 获取最顶层控制器
- (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

- (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}


@end
